package com.work.task.ssh;

import ch.ethz.ssh2.Connection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.io.IOException;


public class SSHConnect {

    private static final Logger logger = LoggerFactory.getLogger(SSHConnect.class);

    private SSHConfig config;
    private Connection connection = null;

    public SSHConfig getConfig() {
        return config;
    }

    public void setConfig(SSHConfig config) {
        this.config = config;
    }

    public SSHConnect(){
        this.config = new SSHConfig();
    }

    public SSHConnect(SSHConfig config){
        this.config = config;
    }

    private boolean isAvailable(){
        if (config!=null && config.isAvailable()){
            return true;
        }
        return false;
    }

    public Connection getConnection(){
        return connection;
    }

    public void close(){
        if (connection!=null){
            connection.close();
        }
    }

    public boolean isConnected(){
        try {

            if (connection!=null){
                connection.close();
                if (isAvailable()){
                    connection.connect();
                    connection.authenticateWithPassword(config.getUserName(),config.getPassword());
                    logger.info("连接成功...");
                    return true;
                }
                logger.error("连接配置不可用...");
                return false;
            }else{
                if (isAvailable()){
                    connection = new Connection(config.getHost(),config.getPort());
                    connection.connect();
                    connection.authenticateWithPassword(config.getUserName(),config.getPassword());
                    logger.info("连接成功...");
                    return true;
                }
                logger.error("连接配置不可用...");
                return false;
            }


        }catch (IOException ex){
            ex.printStackTrace();
            logger.error("服务端连接异常:");
            return false;
        }

    }



}
